package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.LoginMapper;
import com.heima.admin.utils.common.AppJwtUtil;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.admin.service.LoginService;
import com.heima.common.excpetion.CustException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("loginService")
@Transactional
public class LoginServiceImpl extends ServiceImpl<LoginMapper, AdUser> implements LoginService {

    /**
     * 登录业务实现
     *
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDTO adUserDto) {
        if (adUserDto == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);

        if (adUserDto.getName() == null || adUserDto.getPassword() == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);

        LambdaQueryWrapper<AdUser> lambdaQuery = Wrappers.lambdaQuery();
        //从数据库根据用户名查询该用户 有->下一步 无->返回无用户错误
        lambdaQuery.eq(AdUser::getName, adUserDto.getName());
        AdUser adUser = super.getOne(lambdaQuery);

        //数据库没有该用户
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.LOGIN_NOTFOUND_ERROR);
            //TODO 加入Redis
        }
        //用户存在,判断状态
        if (adUser.getStatus() != 9) {
            //用户状态异常返回错误
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        // 取出数据准备进行比对
        String password = adUser.getPassword();
        String salt = adUser.getSalt();
        String passwordResult = DigestUtils.md5DigestAsHex((adUserDto.getPassword() + salt).getBytes());
        // 判断密码是否正确
        if (!passwordResult.equals(password)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //将修改操作交给update方法
        return update(adUser);
    }

    @Transactional
    ResponseResult update(AdUser adUser) {
        //4 修改登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //5 颁发token jwt 令牌
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        // 用户信息返回 VO
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(adUser,adUserVO);
        //6 返回结果（jwt）
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user", adUserVO);

        return ResponseResult.okResult(map);
    }
}
